<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-popconfirm title="提交后无法再修改，确定提交吗?" @confirm="() => handleSubmit()">
            <a-button type="mini" style="margin-left: 1.2%">提交</a-button>
          </a-popconfirm>
          <a-button type="mini" style="margin-left: 1.2%" @click="handleDetailReview()">查看评审表</a-button>
          <buss-contract-requirement-review-modal ref="reviewForm" />
          <act-historic-detail-btn
            style="margin-left: 1.2%"
            :btnType="'mini'"
            :text="'评审表审批历史'"
            :data-id="model.reviewId"
          ></act-historic-detail-btn>
          <a-button type="mini" style="margin-left: 1.2%">追溯原料包材</a-button>
          <a-button type="mini" style="margin-left: 1.2%">查看生产进度表</a-button>
          <a-button type="mini" style="margin-left: 1.2%">查看销售单跟踪</a-button>
          <a-divider style="margin: 5px 0px" />
        </a-row>
        <a-row style="margin-top: 10px">
          <a-col :span="6">
            <a-form-model-item label="年份" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <a-input v-model="model.year" placeholder="请输入年份"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" :disabled="!isAdd" placeholder="请输入单据编号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="产品类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productType">
              <j-dict-select-tag
                type="list"
                v-model="model.productType"
                dictCode="product_type"
                placeholder="请选择产品类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="合同评审表" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reviewCode">
              <a-input v-model="model.reviewCode" disabled placeholder="请输入合同要求评审表"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单据类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="documentType">
              <j-dict-select-tag
                type="list"
                v-model="model.documentType"
                dictCode="marketing_type"
                placeholder="请选择单据类型"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="订货单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <j-dict-select-tag
                type="list"
                disabled
                v-model="model.customerId"
                dictCode="erp_customer,name,id"
                placeholder="请选择客户"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <j-dict-select-tag
                type="list"
                disabled
                v-model="model.customerId"
                dictCode="erp_customer,code,id"
                placeholder="请选择客户"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customer">
              <a-input v-model="model.customer" disabled placeholder="请输入客户类型"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="国家" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="country">
              <j-dict-select-tag
                type="list"
                v-model="model.country"
                dictCode="erp_country,country_name,country_id"
                placeholder="请选择国家"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="包材到位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageInPlace">
              <a-input v-model="model.packageInPlace" placeholder="请输入包材到位"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="交货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryDate">
              <a-input v-model="model.deliveryDate" placeholder="请输入交货日期"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <a-input v-model="model.salesman" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="修改备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="modifyRemarks">
              <a-input v-model="model.modifyRemarks" placeholder="请输入修改备注"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :span="24">
          <a-col :span="24">
            <a-col :span="24"> 产品信息 </a-col>
            <a-col :span="24">
              <!-- 表格 -->
              <j-vxe-table
                keep-source
                bordered
                :ref="refKeys[1]"
                :dataSource="model.erpGoodsPackageList"
                :columns="goodsColumns"
                :disabled="formDisabled"
                @selectRowChange="selectRowChange"
                class="bold-border"
                :rowSelection="true"
                rowSelectionType="radio"
              >
                <template slot="meUnit" slot-scope="text">
                  <span>{{ unitDictOptions[text] }}</span>
                </template>
                <template slot="auUnit" slot-scope="text">
                  <span>{{ zlunitDictOptions[text] }}</span>
                </template>
              </j-vxe-table>
            </a-col>
          </a-col>
        </a-row>
        <a-row> <a-col :span="16">关联包材信息</a-col> </a-row>
        <a-row :gutter="10">
          <a-col :span="24">
            <j-vxe-table
              keep-source
              bordered
              :ref="refKeys[3]"
              :dataSource="packageList"
              :columns="packageColumns"
              :disabled="formDisabled"
              class="bold-border"
            >
            <template v-slot:action="{row}">
                <a v-if="row.patternFile" @click="handlePreviewFile(row)">查看版样</a>
            </template>
            </j-vxe-table>
          </a-col>
        </a-row>
        <a-row style="margin-top: 5px">
          <a-col :span="6">
            <a-form-model-item label="包装要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packReq">
              <a-textarea :rows="10" v-model="model.packReq" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="质量要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaReq">
              <a-textarea :rows="10" v-model="model.formulaReq" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="打码要求" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productionRemark">
              <a-textarea :rows="10" v-model="model.productionRemark" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="评审备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reviewRemark">
              <a-textarea :rows="10" v-model="model.reviewRemark" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="重量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="weight">
              <a-row :gutter="10">
                <a-col :span="18">
                  <a-input-number v-model="model.weight" disabled placeholder="请输入重量" style="width: 100%" />
                </a-col>
                <a-col :span="5">
                  <j-dict-select-tag
                    type="list"
                    disabled
                    v-model="model.weightUnit"
                    dictCode="zl_unit"
                    placeholder="请选择重量单位"
                  />
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="柜数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cabinetCount">
              <a-row :gutter="10">
                <a-col :span="18">
                  <a-input v-model="model.cabinetCount" disabled placeholder="请输入柜数"></a-input>
                </a-col>
                <a-col :span="5">
                  <a-input v-model="model.extra" disabled placeholder="请输入柜数单位"></a-input>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="成交方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="transactionMethod">
              <a-input v-model="model.transactionMethod" disabled placeholder="请输入成交方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="客户其他费用"
              :labelCol="labelCol2"
              :wrapperCol="wrapperCol2"
              prop="otherExpenses"
            >
              <a-input-number
                v-model="model.otherExpenses"
                disabled
                placeholder="请输入客户其他费用"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户订单费用" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="orderFees">
              <a-input-number v-model="model.orderFees" disabled placeholder="请输入客户订单费用" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="货款总值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="amount">
              <a-row :gutter="10">
                <a-col :span="16">
                  <a-input-number v-model="model.totalAmount" placeholder="请输入货款总值" style="width: 100%" />
                </a-col>
                <a-col :span="8">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.currency"
                    dictCode="currency"
                    placeholder="请选择币种"
                  />
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="付款方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="payMethod">
              <a-input v-model="model.payMethod" placeholder="请输入付款方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              label="天数"
              label-width="100px"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="daysArrival"
            >
              <a-input-number v-model="model.daysArrival" placeholder="请输入到货后付全款天数" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="14">
            <a-col :span="24">
              <a-form-model-item
                label="财务备录"
                :labelCol="{ span: 3 }"
                :wrapperCol="{ span: 16, offset: 1 }"
                prop="financialRemarks"
              >
                <a-textarea v-model="model.financeRemark" placeholder="" :rows="4" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="发货港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipPort">
                <a-input v-model="model.shipPort" placeholder="请输入发货港"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="目的港" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="destPort">
                <a-input v-model="model.destPort" placeholder="请输入目的港"></a-input>
              </a-form-model-item>
            </a-col>
          </a-col>
          <a-col :span="10">
            <a-tabs v-model="activeKey" @change="handleChangeTabs">
              <a-tab-pane tab="特殊说明" :key="refKeys[2]" :forceRender="true">
                <a-col :span="24">
                  <a-textarea :rows="10" v-model="model.specialRemark" />
                </a-col>
              </a-tab-pane>
              <a-tab-pane tab="附件列表" :key="refKeys[0]" :forceRender="true">
                <a-col :span="24">
                  <j-upload v-model="model.attachment" text="附件列表"></j-upload>
                </a-col>
              </a-tab-pane>
            </a-tabs>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getFileAccessHttpUrl, getAction, postAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import estar from '../../../estar/oa/util/estar'
import { FilePreview } from '@/utils/tslCommon'
import EditableCell2 from '../../../../components/table/EditableCell2.vue'
import ActHistoricDetailBtn from '@views/flowable/components/ActHistoricDetailBtn.vue'
import BussContractRequirementReviewModal from '@/views/business/review/modules/BussContractRequirementReviewModal.vue'
export default {
  name: 'BussInternationalTradeOrdersForm',
  mixins: [JVxeTableModelMixin],
  components: { EditableCell2, ActHistoricDetailBtn, BussContractRequirementReviewModal },
  props: 
    {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false,
      },
      requirement: {
        type: Object,
        default: {},
        required: false,
      },
    },
    
  data() {
    return {
      modalWidth: 1250,
      isChecked: false,
      packageList: [],
      isAdd:false,
      model: {
        erpGoodsPackageList: [],
        reviewId: '',
        desId: '',
        reviewCode: '',
        customerId: '',
        customerName: '',
        customerCode: '',
        customer: '',
        formulaReq: '',
        packReq: '',
        productionRemark: '',
        reviewRemark: '',
        productType:1,
        cabinetCount: '',
        extra: '',
        transactionMethod: '',
        otherExpenses: '',
        totalAmount: '',
        currency: '',
        financeRemark: '',
        daysArrival: '',
        payMethod: '',
        shipPort: '',
        destPort: '',
        orderFees: '',
        year: '',
        attachment: '',
        status: -2,
        isClose: 0,
        specialRemark: '',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      refKeys: ['bussContractReviewDesFiles', 'bussContractReviewProduct', 'specialRemark', 'packageList'],
      tableKeys: ['bussContractReviewDesFiles'],
      activeKey: 'bussContractReviewDesFiles',
      confirmLoading: false,
      validatorRules: {
        documentType: [{ required: true, message: '请选择单据类型!' }],
        packageInPlace: [{ required: true, message: '请输入包材到位信息!' }],
        deliveryDate: [{ required: true, message: '请输入交付日期!' }],
        totalAmount: [{ required: true, message: '请输入货款总值!' }],
      },
      selectedRowKeys: [],
      // 选中行
      selectedRows: [],
      contractReviewPatternTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            type: JVXETypes.input,
            width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      goodsColumns: [
        {
          title: '产品编号',
          key: 'productCode',
          dataIndex: 'productCode',
          width: 140,
        },
        {
          title: '产品名称',
          key: 'productName',
          dataIndex: 'productName',
          width: 140,
        },
        {
          title: '规格型号',
          key: 'productSpec',
          dataIndex: 'productSpec',
          width: 100,
        },
        {
          title: '生产批号',
          key: 'productBatchNo',
          dataIndex: 'productBatchNo',
          type: JVXETypes.normal,
          width: 300,
        },
        {
          title: '配方号',
          key: 'formulaNo',
          dataIndex: 'formulaNo',
          type: JVXETypes.input,
          width: 150,
        },
        {
          title: '包装方式',
          key: 'packageType',
          dataIndex: 'packageType',
          type: JVXETypes.input,
          width: 150,
        },
        {
          title: '是否生产',
          key: 'isProduction',
          dataIndex: 'isProduction',
          type: JVXETypes.select,
          dictCode: 'yes_no',
          disabled: true,
          width: 120,
        },
        {
          title: '主数量',
          key: 'mainQuantity',
          dataIndex: 'mainQuantity',
          width: 150,
        },
        {
          title: '主单位',
          key: 'meUnit',
          dataIndex: 'meUnit',
          dictCode: 'ji_unit',
          type: JVXETypes.select,
          width: 80,
          disabled: true,
        },
        {
          title: '辅数量',
          key: 'auQuantity',
          dataIndex: 'auQuantity',
          
          width: 100,
        },
        {
          title: '辅单位',
          key: 'auUnit',
          dataIndex: 'auUnit',
          dictCode: 'zl_unit',
          type: JVXETypes.select,
          width: 80,
          disabled: true,
        },
        {
          title: 'BOM版本号',
          key: 'formulaVersion',
          dataIndex: 'formulaVersion',
          width: 80,
        },
        {
          title: 'BOM编码',
          key: 'formulaCode',
          dataIndex: 'formulaCode',
          width: 80,
        },
        {
          title: 'BOM名称',
          key: 'formulaName',
          dataIndex: 'formulaName',
          width: 120,
        },
      ],
      packageColumns: [
        {
          title: '包材编号',
          key: 'packageCode',
          dataIndex: 'packageCode',
          width: 130,
        },
        // {
        //   title: '包材名称',
        //   key: 'packageName',
        //   dataIndex: 'packageName',
        //   width: 200,
        // },
        {
          title: '包材名称',
          key: 'batchNo',
          dataIndex: 'batchNo',
          type: JVXETypes.normal,
          // scopedSlots: { customRender: 'batchNo' },
          width: 300,
        },
        {
          title: '是否自带',
          key: 'isBrought',
          dataIndex: 'isBrought',
          type: JVXETypes.select,
          options: [
            // 下拉选项
            { title: '是', value: '1' },
            { title: '否', value: '0' },
          ],
          width: 100,
        },
        {
          title: '规格型号',
          key: 'packageSpec',
          dataIndex: 'packageSpec',
          width: 120,
        },
        {
          title: '包材类别',
          key: 'packageInOutType',
          dictCode:'package_type',
          dataIndex: 'packageInOutType',
          width: 120,
        },
        {
          title: '损耗率(%)',
          key: 'lossRate',
          dataIndex: 'lossRate',
          width: 120,
        },
        {
          title: '比例数量',
          key: 'proportion',
          dataIndex: 'proportion',
          width: 100,
        },
        {
          title: '包装要求',
          key: 'requirements',
          dataIndex: 'requirements',
          type: JVXETypes.input,
          width: 120,
        },
        {
          title: '材质',
          key: 'materialQuality',
          dataIndex: 'materialQuality',
          width: 120,
        },
        {
          title: '尺寸',
          key: 'size',
          dataIndex: 'size',
          width: 120,
        },
        {
          title: '版样',
          dataIndex: 'patternFile',
          key: 'patternFile',
          type: JVXETypes.file,
          token: true,
        },
        {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        // {
        //   title: '操作',
        //   dataIndex: 'operation',
        //   scopedSlots: { customRender: 'operation' },
        //   align: 'center',
        //   fixed: 'right',
        // },
      ],
      bussContractReviewDesFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'filePath',
            type: JVXETypes.file,
            token: true,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: '',
          },
          {
            title: '附件说明',
            key: 'fileDesc',
            width: '200px',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/review/bussInternationalTradeOrders/add',
        edit: '/review/bussInternationalTradeOrders/edit',
        queryById: '/review/bussInternationalTradeOrders/queryById',
        bussContractReviewDesFiles: {
          list: '/business/bussContractReviewDes/queryBussContractReviewDesFilesByMainId',
        },
        contractReviewPatterns: {
          list: '/contract.pattern/tslContractReviewPattern/list',
          model: '/pattern/erpGoodsPattern/detail',
        },
        review: {
          queryById: '/review/bussContractRequirementReview/queryById',
        },
        upload: '/sys/common/upload',
      },
      openDictOptions: {},
      unitDictOptions: {},
      zlunitDictOptions: {},
      patternDictOptions: {},
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    this.initDictConfig()
    let time = estar.toDate(new Date(), 'yyyy')
    this.model.year = time
  },
  methods: {
    handleDetailReview() {
      getAction(this.url.review.queryById, { id: this.model.reviewId }).then((res) => {
        this.$refs.reviewForm.edit(res.result)
        this.$refs.reviewForm.title = '合同评审表详情'
        this.$refs.reviewForm.disableSubmit = true
      })
    },
    onCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.erpGoodsPackageList]
      const targetProduct = dataSource.find((item) => item.productId === record.productId)
      const packageListSource = [...this.packageList]
      const target = packageListSource.find((item) => item.rowNo === record.rowNo)
      target.batchNo = value
      target.rowNo = target.rowNo + 1
      targetProduct.packageList = packageListSource
      this.model.erpGoodsPackageList = dataSource
      console.log('修改包材批次号', this.model.erpGoodsPackageList, target, value)
    },
    handlePreviewReviewDesFiles(row) {
      if (row && row.filePath) {
        FilePreview(row.filePath)
      }
    },
    handlePattern(row) {
      console.log('选择包材行项目', row)
      if (this.selectedRows) {
        let param = {
          contractReviewId: this.model.reviewId,
          materialId: row.productId,
          packageId: row.packageId,
        }
        getAction(this.url.contractReviewPatterns.list, param).then((res) => {
          console.log('contractReviewPatternList', res)
          if (res.success) {
            this.contractReviewPatternTable.dataSource = res.result.records || res.result
            if (this.contractReviewPatternTable.dataSource && this.contractReviewPatternTable.dataSource.length > 0) {
              return
            }
            const that = thisnumber
            //获取物料版样模板
            let paramErpGoodsPattern = { id: row.productId }
            this.contractReviewPatternTable.dataSource = []
            getAction(this.url.contractReviewPatterns.model, paramErpGoodsPattern).then((res1) => {
              if (res1.success) {
                let record = res1.result
                let obj = {
                  id: 'row_1111',
                  materialId: row.productId,
                  packageId: row.packageId,
                  filePath: record.name,
                  fileDesc: record.remark,
                }
                this.contractReviewPatternTable.dataSource.push(obj)
              }
            })
          }
        })
      }
      //this.$refs.fileInput.click() // 触发文件上传
    },
    initDictConfig() {
      console.log('--我才是真的方法!--')
      //初始化字典 - 开关
      initDictOptions('yes_no').then((res) => {
        console.log(res)
        if (res.success) {
          console.log(res.result)
          this.openDictOptions = res.result
        }
      })
      //初始化字典 - 主单位
      initDictOptions('ji_unit').then((res) => {
        var unitDictOptions = this.unitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            unitDictOptions[item.value] = item.label
          })
        }
        this.unitDictOptions = unitDictOptions
      })
      //初始化字典 - 辅单位
      initDictOptions('zl_unit').then((res) => {
        var zlunitDictOptions = this.zlunitDictOptions
        console.log(res)
        if (res.success) {
          res.result.forEach(function (item, index) {
            zlunitDictOptions[item.value] = item.label
          })
        }
        this.zlunitDictOptions = zlunitDictOptions
      })
      //初始化字典 - 是否有版样
      this.patternDictOptions = {
        1: '是',
        0: '否',
      }
    },
    getSchedulingNumber() {
      let autoCodeUrl = '/sys/fillRule/executeRuleByCode/'
      if (this.model.desFlowType == 2) {
        autoCodeUrl += 'sales_order_code_international'
      } else {
        autoCodeUrl += 'sales_order_code_domestic'
      }
      postAction(autoCodeUrl, {}).then((res) => {
        this.model.code = res.result
        this.addAfter()
        this.$forceUpdate()
      })
    },
    add() {
      console.log('--------')
      this.isAdd=true;
      this.validatorRules= {
        code: [
              { required: true},
              { validator: (rule, value, callback) => validateDuplicateValue('buss_international_trade_orders', 'code', value, this.model.code, callback)},
           ],
        documentType: [{ required: true, message: '请选择单据类型!' }],
        packageInPlace: [{ required: true, message: '请输入包材到位信息!' }],
        deliveryDate: [{ required: true, message: '请输入交付日期!' }],
        totalAmount: [{ required: true, message: '请输入货款总值!' }],
      };
      // this.edit(this.modelDefault);
      console.log(this.requirement)
      this.model.reviewId = this.requirement.id
      this.model.desId = this.requirement.desId
      this.model.reviewCode = this.requirement.code
      this.model.productionRemark = this.requirement.productionRemark
      //评审备注=评审表备注+报价备注
      this.model.reviewRemark = this.requirement.remark+this.requirement.quoteRemark
      this.model.otherExpenses = this.requirement.otherExpenses
      this.model.totalAmount = this.requirement.amount
      this.model.currency = this.requirement.currency
      this.model.financeRemark = this.requirement.financeRemark
      this.model.specialRemark = ''
      if(this.requirement.schedulingNumber && this.requirement.schedulingNumber!='/' && this.requirement.schedulingNumber!='无'){
        this.model.code = this.requirement.schedulingNumber
        this.addAfter()
      }else{
        this.getSchedulingNumber();
      }
      
      
      const that = this
      getAction('/business/bussContractReviewDes/queryById', { id: this.requirement.desId }).then((res) => {
        console.log('获取合同评审说明', res)
        let records = res.result
        if (records != null) {
          this.model.customerId = records.customerId
          this.model.customer = records.customer
          this.model.salesman = records.salesman
          this.model.formulaReq = records.formulaReq
          this.model.packReq = records.packReq
          this.model.weight = records.weight
          this.model.weightUnit = records.weightUnit
          this.model.cabinetCount = records.cabinetCount
          this.model.extra = records.extra
          this.model.payMethod = records.payMethod
          this.model.transactionMethod = records.transactionMethod
          this.model.daysArrival = records.daysArrival
          this.model.shipPort = records.shipPort
          this.model.destPort = records.destPort
          getAction('/base/erpCustomer/queryById', { id: this.model.customerId }).then((res1) => {
            if (res1.success) {
              let cu = res1.result
              console.log('客户', cu)
              that.model.country = cu.countryId
              that.$forceUpdate()
            }
          })
        }
      })
      
    },

    edit(record) {
      getAction(this.url.queryById, { id: record.id }).then((res) => {
        if (res.success) {
          this.model = Object.assign({}, res.result)
          this.model.erpGoodsPackageList = res.result.productList
          if (this.model.erpGoodsPackageList && this.model.erpGoodsPackageList.length > 0) {
            this.packageList = this.model.erpGoodsPackageList[0].packageList
            console.log('编辑营销订单：', this.model, this.model.erpGoodsPackageList, this.packageList)
          }
        }
      })
      this.visible = true
    },
    addAfter() {
      let _this = this
      console.log(_this.model, '_this.model')
      getAction('/review/bussContractRequirementReview/reviewProduct/ByReviewId', { id: this.model.reviewId }).then(
        (res) => {
          let erpGoodsList = res.result
          console.log('11111', res)
          erpGoodsList.forEach(function (item, index) {
            console.log(item, _this.model.code, index, '获取评审表关联物料')
            let detail = {}
            detail.reviewProductId = item.orderProductId;
            detail.productId = item.id
            detail.reviewId = item.reviewId
            detail.rowKey = item.id
            detail.orderCode = _this.model.code
            detail.productCode = item.code
            detail.productName = item.name
            detail.productBatchNo = _this.model.code + '#' + item.name
            detail.coRate = item.coRate
            detail.productSpec = item.noneSpec
            detail.meUnit = item.meUnit
            detail.auUnit = item.auUnit
            detail.formulaId = item.formulaId
            detail.formulaCode = item.formulaCode
            detail.formulaName = item.formulaName
            detail.formulaVersion = item.formulaYear
            detail.formulaNo = item.formulaNo
            detail.number = item.formulaNo
            detail.packageType = item.packageType
            detail.viscosity=item.viscosity

            detail.packageList = item.packageVos.map((pitem) => {
              let pid = pitem.id
              return {
                ...pitem,
                packageSpec: item.noneSpec,
                reviewPackageId: pid,
                productId: detail.productId,
                orderCode: _this.model.code,
                batchNo: _this.model.code + '#' + pitem.packageName,
                rowNo: pid,
              }
            })
            console.log('包材信息', item.packageVos, detail.packageList)
            detail.formularVos = item.formularVos.map((item) => {
              return { ...item, rowNo: item.id }
            })
            detail.mainQuantity = item.mainQuantity
            detail.auQuantity = item.auxiliaryQuantity
            detail.isProduction = item.isProduction
            _this.model.erpGoodsPackageList.push(detail)
          })
          console.log('_this.model.erpGoodsPackageList', _this.model.erpGoodsPackageList)
        }
      )

      // 加载子表数据
      // if (this.model.desId) {
      //   let params = { id: this.model.desId }
      //   this.requestSubTableData(this.url.bussContractReviewDesFiles.list, params, this.bussContractReviewDesFilesTable)
      // }
    },
    selectRowChange({ type, action, selectedRows, $event }) {
      console.log('选择事件', type, action, selectedRows, $event)
      if (selectedRows.length.length > 1 || selectedRows.length.length == 0) {
        $event.$table.clearFilter()
      } else {
        if (this.model.erpGoodsPackageList.length > 0) {
          const row = selectedRows[0]
          const dataSource = [...this.model.erpGoodsPackageList]
          const target = dataSource.find((item) => item.productId === row.productId)
          this.packageList = target.packageList.map((item) => {
            item.rowNo = item.rowNo + 1
            return item
          })
          console.log('产品对应包材信息！', this.packageList)

          // if (target.packageList != null && target.packageList.length > 0) {

          // }
        }
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      if (this.selectedRows.length > 0 && this.selectedRows[0] != null) {
        const key = 'goodsId'
        this.selectedRowKeys = [selectedRowKeys.filter((item) => item !== this.selectedRowKeys[0])[0]]
        this.selectedRows = [selectedRows.filter((item) => item[key] !== this.selectedRows[0][key])[0]]
      } else {
        this.selectedRowKeys = [selectedRowKeys[0]]
        this.selectedRows = [selectedRows[0]]
      }
      console.log(this.selectedRows)
      if (this.selectedRows[0] != null) {
        const dataSource = [...this.model.erpGoodsPackageList]
        const target = dataSource.find((item) => item.goodsId === this.selectedRows[0].goodsId)
        if (target.packageVos != null && target.packageVos.length > 0) {
          this.packageList = target.packageVos
        } else {
          this.packageList = []
        }
      }
    },
    handleSubmit() {
      //改成已审批的状态
      this.model.status = 999
      this.submitForm()
    },
    submitForm() {
      const that = this
      this.model.productList = this.model.erpGoodsPackageList
      console.log(this.model)
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          console.log('----------------------------------------')
          console.log(this.model)
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handlePreviewFile(row) {
      console.log(row,"版样文件")
      FilePreview(row.patternFile)
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
  },
}
</script>
